package {
	import flash.geom.*;
	import flash.display.*;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.*;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.*;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;

	import cmodule.jpeg.CLibInit;

	public class test extends Sprite
	{
		private var text:TextField = new TextField();
		public function test()
		{
			addChild(text);
			text.wordWrap = true;
			text.defaultTextFormat = new TextFormat(null,20,0x3399ee);
			text.text = "hello简介将简介建立集建立";
			var w:int = 2040;
			var h:int = 2040;
			var bmpd:BitmapData = new BitmapData(w,h,true,0xffffffff);
			bmpd.draw(text);
			addChild(new Bitmap(bmpd)).y=100;

			var bytes:ByteArray = bmpd2bytes(bmpd);
			//bytes = bmpd2bytes(bmpd);

			trace("as3 outbytes length: ",bytes.length);
			loadBytes(bytes,loaded);
		}

		//import cmodule.jpeg.CLibInit;
		private static var lib:Object = new cmodule.jpeg.CLibInit().init();
		public static function bmpd2bytes(bmpd:BitmapData):ByteArray
		{
			var rect:Rectangle = bmpd.rect;
			var bmpdBytes:ByteArray = bmpd.getPixels(rect);
			bmpdBytes.position = 0;
			trace("as3 inbytes length: ",bmpdBytes.length);
			var bytes:ByteArray = new ByteArray();
			bytes = lib.encode(bmpd.width,bmpd.height,bmpdBytes,80,bytes);
			bytes.position = 0;
			return bytes;
		}

		public static function loadBytes(bytes:ByteArray,_loaded:Function):Loader
		{
			if(_loaded ==null)return null;
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, _loaded);
			loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _loaded);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _loaded);
			var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
			context.allowCodeImport = true;
			loader.loadBytes(bytes,context);
			return loader;
		}

		private function loaded(e:Event=null):void
		{
			if(e.type == Event.COMPLETE)
			{
				var bmp:Bitmap = e.target.content;
				addChild(bmp).x = 100;
				//bmp.smoothing = true;
			}else{
				text.text = String(e);
				trace(e);
			}
		}
	}
}
